"""
配置管理模块
负责处理配置文件的读取、保存和规则管理
"""
import os
import yaml
import logging

# 配置日志
logger = logging.getLogger(__name__)


class ConfigManager:
    def __init__(self, config_path='config.yaml'):
        self.config_path = config_path
        # 默认服务器配置
        self.default_server_config = {
            'proxy': {
                'host': '0.0.0.0',
                'port': 8080,
                'default_target_port': 80
            },
            'web': {
                'host': '0.0.0.0',
                'port': 5001
            },
            'system_proxy': {
                'host': '127.0.0.1',
                'port': 8080
            }
        }
        logger.info(f"初始化配置管理器，配置文件: {config_path}")
    
    def load_config(self):
        """加载配置"""
        if not os.path.exists(self.config_path):
            return {'rules': []}
        with open(self.config_path, 'r') as f:
            return yaml.safe_load(f)
    
    def save_config(self, config):
        """保存配置"""
        with open(self.config_path, 'w') as f:
            yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
    
    def add_rule(self, rule):
        """添加规则"""
        config = self.load_config()
        config['rules'].append(rule)
        self.save_config(config)
    
    def update_rule(self, index, rule):
        """更新规则"""
        config = self.load_config()
        if 0 <= index < len(config['rules']):
            config['rules'][index] = rule
            self.save_config(config)
    
    def delete_rule(self, index):
        """删除规则"""
        config = self.load_config()
        if 0 <= index < len(config['rules']):
            config['rules'].pop(index)
            self.save_config(config)
    
    def toggle_rule(self, index):
        """切换规则的启用/禁用状态"""
        config = self.load_config()
        if 0 <= index < len(config['rules']):
            rule = config['rules'][index]
            # 切换enabled状态，默认为True
            rule['enabled'] = not rule.get('enabled', True)
            self.save_config(config)
            return rule['enabled']
        return None
    
    def set_rule_enabled(self, index, enabled):
        """设置规则的启用/禁用状态"""
        config = self.load_config()
        if 0 <= index < len(config['rules']):
            config['rules'][index]['enabled'] = enabled
            self.save_config(config)
            return True
        return False
    
    def get_server_config(self):
        """获取服务器配置，如果不存在则返回默认配置"""
        config = self.load_config()
        server_config = config.get('server', {})
        
        # 合并默认配置和用户配置
        result = {}
        for service_name, default_service_config in self.default_server_config.items():
            user_service_config = server_config.get(service_name, {})
            result[service_name] = {**default_service_config, **user_service_config}
        
        logger.debug(f"获取服务器配置: {result}")
        return result
    
    def get_proxy_config(self):
        """获取代理服务器配置"""
        server_config = self.get_server_config()
        return server_config['proxy']
    
    def get_web_config(self):
        """获取Web服务器配置"""
        server_config = self.get_server_config()
        return server_config['web']
    
    def get_system_proxy_config(self):
        """获取系统代理配置"""
        server_config = self.get_server_config()
        return server_config['system_proxy']
    
    def validate_server_config(self, server_config=None):
        """验证服务器配置的有效性"""
        if server_config is None:
            server_config = self.get_server_config()
        
        errors = []
        
        for service_name, service_config in server_config.items():
            # 验证端口范围
            port = service_config.get('port')
            if not isinstance(port, int) or port < 1 or port > 65535:
                errors.append(f"{service_name}.port 必须是1-65535之间的整数")
            
            # 验证host格式
            host = service_config.get('host')
            if not isinstance(host, str) or not host.strip():
                errors.append(f"{service_name}.host 不能为空")
        
        # 检查端口冲突 (proxy和system_proxy可以使用相同端口)
        ports = {}
        for service_name, service_config in server_config.items():
            port = service_config.get('port')
            if port in ports:
                # proxy和system_proxy可以使用相同端口，因为它们指向同一个服务
                existing_service = ports[port]
                if not ((service_name == 'system_proxy' and existing_service == 'proxy') or 
                        (service_name == 'proxy' and existing_service == 'system_proxy')):
                    errors.append(f"端口冲突: {service_name} 和 {existing_service} 都使用端口 {port}")
            else:
                ports[port] = service_name
        
        if errors:
            logger.error(f"服务器配置验证失败: {errors}")
            return False, errors
        
        logger.info("服务器配置验证通过")
        return True, []
    
    def update_server_config(self, server_config):
        """更新服务器配置"""
        # 验证配置
        is_valid, errors = self.validate_server_config(server_config)
        if not is_valid:
            raise ValueError(f"配置验证失败: {errors}")
        
        # 加载当前配置
        config = self.load_config()
        config['server'] = server_config
        
        # 保存配置
        self.save_config(config)
        logger.info("服务器配置已更新")